import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:refresh_page/src/refresh_page_configuration.dart';
import 'package:refresh_page/src/refresh_page_controller.dart';
import 'package:refresh_page/src/refresh_page_enum.dart';

import 'behavior.dart';
import 'typedefs.dart';

class RefreshWidget<C extends RefreshPageController> extends StatefulWidget {
  final String? tag;

  ///是否启用上拉加载
  final bool enablePullUp;

  ///是否启用下拉刷新
  final bool enablePullDown;

  final Widget child;

  /// 自定义加载中状态构建器，优先级高于全局配置
  final LoadingBuilder? loadingBuilder;

  /// 自定义空状态构建器，优先级高于全局配置
  final EmptyBuilder? emptyBuilder;

  /// 自定义错误状态构建器，优先级高于全局配置
  final ErrorBuilder? errorBuilder;

  /// 自定义状态显示位置构建器，允许用户自定义状态显示位置
  final Widget Function(Widget stateWidget)? statePositionBuilder;

  /// 空状态是否覆盖整个区域，为false时通过statePositionBuilder回调
  final bool emptyOverlay;

  /// 错误状态是否覆盖整个区域，为false时通过statePositionBuilder回调
  final bool errorOverlay;

  /// 加载状态是否覆盖整个区域，为false时通过statePositionBuilder回调
  final bool loadingOverlay;

  C get controller => Get.find<C>(tag: tag);

  const RefreshWidget({
    super.key,
    this.tag,
    this.enablePullUp = true,
    this.enablePullDown = true,
    required this.child,
    this.loadingBuilder,
    this.emptyBuilder,
    this.errorBuilder,
    this.statePositionBuilder,
    this.emptyOverlay = true,
    this.errorOverlay = true,
    this.loadingOverlay = true,
  });

  @override
  State<RefreshWidget> createState() => _RefreshWidgetState<C>();
}

class _RefreshWidgetState<C extends RefreshPageController>
    extends State<RefreshWidget> with AutomaticKeepAliveClientMixin {
  @override
  Widget build(BuildContext context) {
    super.build(context);

    final config = RefreshPageConfiguration.of(context);

    return SizedBox.expand(
      child: Stack(
        alignment: Alignment.center,
        children: [
          ///刷新控件
          _refreshWidget(config),

          ///加载中
          _buildStateWidget(
            stateType: LoadState.first,
            overlay: widget.loadingOverlay,
            builder: () => _loadingWidget(config),
          ),

          ///空页面
          _buildStateWidget(
            stateType: LoadState.empty,
            overlay: widget.emptyOverlay,
            builder: () => _emptyWidget(config),
          ),

          ///错误页面
          _buildStateWidget(
            stateType: LoadState.error,
            overlay: widget.errorOverlay,
            builder: () => _errorWidget(config),
          ),
        ],
      ),
    );
  }

  Widget _buildStateWidget({
    required LoadState stateType,
    required bool overlay,
    required Widget Function() builder,
  }) {
    return Obx(() {
      final isVisible = widget.controller.loadState.value == stateType;
      if (!isVisible) return const SizedBox.shrink();

      final stateWidget = builder();

      // 如果不是覆盖模式且提供了位置构建器，使用位置构建器
      if (!overlay && widget.statePositionBuilder != null) {
        return widget.statePositionBuilder!(stateWidget);
      }

      // 否则默认覆盖在整个区域
      return stateWidget;
    });
  }

  @override
  bool get wantKeepAlive => true;

  Widget _refreshWidget(RefreshPageConfiguration? config) {
    return Obx(
      () {
        return Visibility(
          visible: widget.controller.loadState.value == LoadState.success,
          child: ScrollConfiguration(
            behavior: OverScrollBehavior(),
            child: SmartRefresher(
              header: config?.header,
              footer: config?.footer,
              controller: widget.controller.refreshController,
              enablePullDown: widget.enablePullDown,
              enablePullUp: widget.enablePullUp,
              onRefresh: widget.controller.refreshData,
              onLoading: widget.controller.loadMore,
              child: widget.child,
            ),
          ),
        );
      },
    );
  }

  Widget _loadingWidget(RefreshPageConfiguration? config) {
    // 优先使用组件自身的构建器
    if (widget.loadingBuilder != null) {
      return widget.loadingBuilder!(context, widget.controller);
    }

    // 其次使用全局配置的构建器
    if (config?.loadingBuilder != null) {
      return config!.loadingBuilder!(context, widget.controller);
    }

    // 默认加载指示器
    return const Center(
      child: CircularProgressIndicator(),
    );
  }

  Widget _emptyWidget(RefreshPageConfiguration? config) {
    // 优先使用组件自身的构建器
    if (widget.emptyBuilder != null) {
      return widget.emptyBuilder!(context, widget.controller);
    }

    // 其次使用全局配置的构建器
    if (config?.emptyBuilder != null) {
      return config!.emptyBuilder!(context, widget.controller);
    }

    // 默认空状态
    return const Center(
      child: Text('暂无数据'),
    );
  }

  Widget _errorWidget(RefreshPageConfiguration? config) {
    // 优先使用组件自身的构建器
    if (widget.errorBuilder != null) {
      return widget.errorBuilder!(
          context, widget.controller, widget.controller.reload);
    }

    // 其次使用全局配置的构建器
    if (config?.errorBuilder != null) {
      return config!.errorBuilder!(
          context, widget.controller, widget.controller.reload);
    }

    // 默认错误状态
    return Center(
      child: ElevatedButton(
        onPressed: widget.controller.reload,
        child: const Text('重新加载'),
      ),
    );
  }
}
